
export class TypedArrayList<T extends Uint16Array | Float32Array | Uint8Array> {
    private _array: T;
    private _typedArrayConstructor: (new (length: number) => T);

    // 表示使用过的元素
    private _length: number;
    private _capacity: number;

    public get length() :number{
        return this._length;
    }

    public get capacity():number {
        return this._capacity;
    }

    public  get typedArray():T{
        return this._array
    }

    public constructor(
        typedArrayConstructor: new (capacity: number) => T,
        capacity: number = 8
    ) {
        if (capacity < 1){
            throw new Error('容量至少为1');
        }
        this._typedArrayConstructor = typedArrayConstructor;
        this._capacity = capacity;
        this._array = new this._typedArrayConstructor(this._capacity);
        this._length = 0;
    }

    public push(num: number): number {
        if (this._length >= this._capacity) {
            // 进行扩容
            this._capacity += this._capacity;
            console.log(`进行扩容,扩容后:${this._capacity}`);

            let oldArray = this._array;
            this._array = new this._typedArrayConstructor(this._capacity);
            this._array.set(oldArray);
        }
        this._array[this._length++] = num;
        return this._length;
    }

    /**
     * 注意和 slice 方法 的区别
     * @param start
     * @param end
     */
    public subarray(start: number = 0, end: number = this.length): T {
        return this._array.subarray(start, end) as T;
    }

    public slice(start: number = 0, end: number = this.length): T {
        return this._array.slice(start, end) as T;
    }

    public clear():void{
        this._length = 0;
    }
    public at(idx:number):number{
        if (idx < 0 || idx >= this.length){
            throw new Error(`索引越界...`);
        }
        return  this._array[idx];
    }
}

